import React, { useState, useEffect } from 'react';
import { Tag, Input, message, Modal, Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import styles from './TagSelector.module.css';
import { Tag as TagType } from '@/services/tagService';

interface TagSelectorProps {
  // 选中的标签
  value?: TagType[];
  // 标签变化回调
  onChange?: (tags: TagType[]) => void;
  // 获取所有标签的API
  fetchTags: () => Promise<TagType[]>;
  // 添加新标签的API
  addTag?: (name: string) => Promise<TagType>;
  // 标签颜色
  tagColors?: string[];
  // 是否显示添加按钮
  showAddButton?: boolean;
}

const DEFAULT_COLORS = [
  'magenta', 'red', 'volcano', 'orange', 'gold', 
  'lime', 'green', 'cyan', 'blue', 'geekblue', 'purple'
];

const TagSelector: React.FC<TagSelectorProps> = ({
  value = [],
  onChange,
  fetchTags,
  addTag,
  tagColors = DEFAULT_COLORS,
  showAddButton = true
}) => {
  const [allTags, setAllTags] = useState<TagType[]>([]);
  const [selectedTags, setSelectedTags] = useState<TagType[]>(value);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [newTagName, setNewTagName] = useState('');
  const [loading, setLoading] = useState(false);

  // 获取所有标签
  useEffect(() => {
    const loadTags = async () => {
      try {
        setLoading(true);
        const tags = await fetchTags();
        setAllTags(tags);
        setLoading(false);
      } catch (error) {
        console.error('Failed to fetch tags:', error);
        message.error('获取标签失败');
        setLoading(false);
      }
    };
    loadTags();
  }, [fetchTags]);

  // 同步外部value值
  useEffect(() => {
    if (value && JSON.stringify(value) !== JSON.stringify(selectedTags)) {
      setSelectedTags(value);
    }
  }, [value]);

  // 处理标签点击
  const handleTagClick = (tag: TagType) => {
    const isSelected = selectedTags.some(item => item.id === tag.id);
    let newSelectedTags: TagType[];
    
    if (isSelected) {
      newSelectedTags = selectedTags.filter(item => item.id !== tag.id);
    } else {
      newSelectedTags = [...selectedTags, tag];
    }
    
    setSelectedTags(newSelectedTags);
    onChange?.(newSelectedTags);
  };

  // 打开添加标签模态框
  const showAddTagModal = () => {
    setIsModalVisible(true);
    setNewTagName('');
  };

  // 处理添加标签
  const handleAddTag = async () => {
    if (!newTagName.trim()) {
      message.warning('标签名不能为空');
      return;
    }

    // 检查是否存在同名标签
    if (allTags.some(tag => tag.name === newTagName.trim())) {
      message.warning('标签已存在');
      return;
    }

    try {
      if (addTag) {
        setLoading(true);
        const newTag = await addTag(newTagName.trim());
        setAllTags([...allTags, newTag]);
        
        // 自动选中新添加的标签
        const newSelectedTags = [...selectedTags, newTag];
        setSelectedTags(newSelectedTags);
        onChange?.(newSelectedTags);
        
        setLoading(false);
        setIsModalVisible(false);
        message.success('添加标签成功');
      }
    } catch (error) {
      console.error('Failed to add tag:', error);
      message.error('添加标签失败');
      setLoading(false);
    }
  };

  // 获取标签颜色
  const getTagColor = (tag: TagType) => {
    const isSelected = selectedTags.some(item => item.id === tag.id);
    if (!isSelected) return 'default';
    return tagColors[tag.id % tagColors.length];
  };

  return (
    <div className={styles.tagSelector}>
      <div className={styles.tagsWrapper}>
        {allTags.map(tag => (
          <Tag
            key={tag.id}
            className={styles.tagItem}
            color={getTagColor(tag)}
            onClick={() => handleTagClick(tag)}
          >
            {tag.name}
          </Tag>
        ))}
        {showAddButton && addTag && (
          <Tag 
            className={styles.addTagButton} 
            onClick={showAddTagModal}
            icon={<PlusOutlined />}
          >
            添加标签
          </Tag>
        )}
      </div>

      <Modal
        title="添加新标签"
        open={isModalVisible}
        onOk={handleAddTag}
        onCancel={() => setIsModalVisible(false)}
        confirmLoading={loading}
      >
        <Input
          placeholder="请输入标签名称"
          value={newTagName}
          onChange={e => setNewTagName(e.target.value)}
          maxLength={20}
          autoFocus
        />
      </Modal>
    </div>
  );
};

export default TagSelector; 